package yi.wuhenbot.Utils;

import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import yi.wuhenbot.Controller.BotController;

/**
 * 机器人token工具类
 * @author wuhen
 */
@Component
public class BotTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(BotController.class);

    /**
     * 机器人appId
     */
    @Value("${bot.appid}")
    private String botAppId;

    /**
     * 机器人appSecret
     */
    @Value("${bot.secret}")
    private String botAppSecret;

    /**
     * 请求 <a href="https://bots.qq.com/app/getAppAccessToken">.</a> 接口获取机器人token
     * @return 机器人token
     */
    public String getToken() {
        String url = "https://bots.qq.com/app/getAppAccessToken";
        // 检查 appId 和 appSecret 是否为空
        if (botAppId == null || botAppId.isEmpty() || botAppSecret == null || botAppSecret.isEmpty()) {
            throw new IllegalStateException("AppId or AppSecret 配置异常.");
        }
        //System.out.println("机器人参数：botAppId = " + botAppId);
        //logger.info("机器人参数：botAppSecret = " + botAppSecret);
        //logger.info("机器人参数：url = " + url);

        // 构造请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("appId", botAppId);
        requestBody.put("clientSecret", botAppSecret);

        // 发送POST请求
        String result = HttpUtil.post(url, requestBody.toJSONString());
        //logger.info("机器人参数：result = " + result);

        // 解析JSON
        JSONObject jsonObject = JSONObject.parseObject(result);

        // 检查返回的JSON中是否有错误信息
        if (jsonObject.containsKey("code") && jsonObject.getIntValue("code") != 0) {
            throw new RuntimeException("Failed to get token: " + jsonObject.getString("message"));
        }

        // 获取access_token
        String accessToken = jsonObject.getString("access_token");
        if (accessToken == null || accessToken.isEmpty()) {
            throw new RuntimeException("Access token is missing in the response.");
        }

        return accessToken;
    }

    public String getAppSecret() {
        return botAppSecret;
    }
}
